package com.mark.interceptor;

import com.mark.enums.UserStateEnum;
import com.mark.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by Mark on 2018/4/11.
 * 拦截器
 */

@Slf4j
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("utf-8");//防止请求信息的中文乱码
        String url =request.getRequestURI();

        //对用户是否登录进行判断
        User currentUser = (User) request.getSession().getAttribute(UserStateEnum.CURRENT_USER.getStateInfo());
        if(currentUser == null){
            response.setContentType("application/json; charset=utf-8");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status",10);
            PrintWriter writer = response.getWriter();
            writer.write(jsonObject.toString());
            writer.flush();
            writer.close();
            log.info("拦截器：用户未登录");
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}
